package rabbitmq_demo

import (
	"gitee.com/lihaiping1603/utils/log"
	amqp "github.com/rabbitmq/amqp091-go"
)

type client struct {
	conn    *amqp.Connection
	channel *amqp.Channel
}

func (c *client) create(url, exchange, kind string) error {
	conn, err := amqp.Dial(url)
	if err != nil {
		log.Error("AMQP dial %s,err:%s", url, err.Error())
		return err
	}
	channel, err := conn.Channel()
	if err != nil {
		log.Error("AMQP get Channel err:%s", err.Error())
		return err
	}
	//声明交换器
	if err = channel.ExchangeDeclare(
		exchange, // name of the exchange
		kind,     // type
		true,     // durable 持久
		false,    // delete when complete
		false,    // internal
		false,    // noWait
		nil,      // arguments
	); err != nil {
		log.Error("AMQP exchange:%s kind:%s declare err: %s", exchange, kind, err.Error())
		return err
	}
	c.conn = conn
	c.channel = channel
	return nil
}

func (c *client) destroy() error {
	if err := c.channel.Close(); err != nil {
		log.Error("AMQP channel close error: %s", err.Error())
		return err
	}

	if err := c.conn.Close(); err != nil {
		log.Error("AMQP connection close error: %s", err.Error())
		return err
	}
	return nil
}
